package org.skatiger.jrove.renderer;

import java.io.IOException;

import org.skatiger.jrove.ViewContext;
import org.skatiger.jrove.component.UIComponent;
import org.skatiger.jrove.component.UIViewRoot;
import org.skatiger.jrove.util.StringUtils;

public class HtmlRendererBase extends Renderer {
    /**
     * Renders the client ID as an "id".
     */
    protected void renderId(ViewContext context,
            UIComponent component,
            boolean must) throws IOException {
        if (must || shouldRenderId(context, component)) {
            String clientId = getClientId(context, component);
            context.getResponseWriter().writeAttribute(Html.ID_ATTR, clientId,
                    Html.ID_ATTR);
        }
    }

    /**
     * Renders the client ID as an "id".
     */
    protected void renderId(ViewContext context, UIComponent component) throws IOException {
        renderId(context, component, isMustRenderId());
    }

    protected boolean isMustRenderId() {
        return false;
    }

    /**
     * Returns the client ID that should be used for rendering (if
     * {@link #shouldRenderId} returns true).
     */
    protected String getClientId(ViewContext context, UIComponent component) {
        return component.getClientId(context);
    }

    /**
     * Returns true if the component should render an ID. Components that
     * deliver events should always return "true".
     * 
     * @todo Is this a bottleneck? If so, optimize!
     */
    protected boolean shouldRenderId(ViewContext context, UIComponent component) {
        String id = component.getId();

        // Otherwise, if ID isn't set, don't bother
        if (id == null)
            return false;

        // ... or if the ID was generated, don't bother
        if (id.startsWith(UIViewRoot.UNIQUE_ID_PREFIX))
            return false;

        return true;
    }

    public String calculateUrl(ViewContext context,
            UIComponent component,
            String attributeName) {
        String value = (String) component.getAttributes().get(attributeName);
        if (StringUtils.isNotEmpty(value)) {
            String contextPath = context.getExternalContext()
                    .getRequestContextPath();
            if (StringUtils.isEmpty(contextPath)) {
                return value;
            }
            if (value.startsWith(Html.HREF_PATH_SEPARATOR)) {
                if (!value.startsWith(contextPath)) {
                    value = contextPath + value;
                }
            }
        }
        return value;
    }
}
